import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Analysis {

    private TextDealer TD;

    Analysis(String file1,String file2) {
        this.TD = new TextDealer(file1,file2);
    }

    public void writeResult()throws Exception {
        try {
            this.TD.writeIntoTxt(this.sortByFrequency());
        }finally {
        }
    }
    private String[] getWords(String content) {
        String[] words = content.split("\\s+");
        return words;
    }

    private HashMap<String, Integer> analyseWordFre() throws Exception {
        HashMap<String, Integer> word_frequency = new HashMap<>();
        try {
            String[] words = this.getWords(this.TD.readByFileReader());
            Integer tmp;
            for (String word : words) {
                tmp = word_frequency.put(word,1);
                if(tmp!=null){
                    word_frequency.put(word,++tmp);
                }
            }
        } finally {

        }

        return word_frequency;
    }

    private String[] toStringArray() throws Exception{

        List<String> list = new ArrayList<>();
        HashMap<String,Integer> w_f = this.analyseWordFre();
        try {
            for(Map.Entry<String,Integer> entry : w_f.entrySet()){
                String str = entry.getKey()+" "+entry.getValue();
                list.add(str);
            }
        }finally{
        }
        return (String[])list.toArray();
    }

    private String[] sortByFrequency() throws Exception {
        String []strs = null;
        try {
            strs = this.toStringArray();
            //冒泡排序
            for (int i = 1; i < strs.length; i++) {
                boolean flag = true;
                for(int j = 0;j<strs.length-i;j++){
                    if(!moreFrequent(strs[j],strs[j+1])){
                      String tmp = strs[j];
                      strs[j] = strs[j+1];
                      strs[j+1] = tmp;
                      flag = false;
                    }
                }
                if(flag) break;
            }
        }finally {
        }
        return strs;
    }

    private boolean moreFrequent(String str1,String str2){
        int str1F = Integer.valueOf(str1.substring(str1.indexOf(" ")));
        int str2F = Integer.valueOf(str1.substring(str2.indexOf(" ")));
        if(str1F>str2F)return true;
        else return false;
    }

}